package com.example.coreshopapp.http;

import static androidx.core.content.ContextCompat.startActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.bean.LoginData;
import com.example.coreshopapp.bean.ResponseFormRes;
import com.example.coreshopapp.bean.ResponseRes;
import com.example.coreshopapp.bean.SysuserData;
import com.example.coreshopapp.net.BaseApplication;
import com.example.coreshopapp.ui.LoginActivity;

import java.net.SocketTimeoutException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AccessNet {
    // 初始化BaseAPPlication里面的Retrofit，并将RegisterSerivce里面的url和参数传入，拿到的数据
    private static RegisterSerivce registerSerivce = BaseApplication.getInstance().getRetrofit().create(RegisterSerivce.class);


    public static boolean postDataNet(final Handler mHandler, final String url, final int urlno, String datainfo) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, datainfo); // datainfo json传递请求参数
        registerSerivce.postDataNet(url, body,"Bearer " + Constants.AppConstVars.token)
                .enqueue(new Callback<ResponseRes>() {
            @Override
            public void onResponse(Call<ResponseRes> call, Response<ResponseRes> response) {
                //  boolean ispassed=false;
                Message message = mHandler.obtainMessage();
                message.arg2 = urlno;
                message.what = 9901;
                if (response.isSuccessful()) {
                    // 响应成功
                    Log.d("postDataNet成功响应", response.body().toString());
                    if (response.body().getCode() == 0) {
//                        Log.d("postDataNet成功返回数据", response.body().toString());
                        // 数据为0，后台正确响应
                        message.what = 9900;
                        message.obj = response.body().getData();
                    } else if (response.body().getCode() == 401) {
                        message.what = 9904;
                        message.obj = "登录过期，请重新登录";
                        Constants.AppConstVars.token = "";
                        Constants.AppConstVars.sysUser = new SysuserData();
                    } else {
                        // 数据不为0，后台错误响应
                        Log.d("postDataNet错误返回数据", response.body().getMsg().toString());
                        message.what = 9901;
                        message.obj = response.body().getMsg();
                    }
                } else {
                    Log.d("超时", ": ");
                    // 超时
                    message.what = 9901;
                    message.obj = "请求失败，请稍后重试";
                }
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<ResponseRes> call, Throwable t) {
                Log.d("postDataNet错误返回数据onFailure", "");
                Message message = mHandler.obtainMessage();
                message.arg2 = urlno;
                message.what = 9902;
                try {
                    if(t instanceof SocketTimeoutException) {
                        message.what = 9901;
                        message.obj = "请求超时，请重试";
                    } else {
                        if (t.getMessage() == null) {
                            message.obj = t.getClass().toString();
                        } else {
                            message.obj = t.getMessage();
                        }
                    }

                } catch (Exception ex) {
                    message.obj = ex.getMessage();
                }
                mHandler.sendMessage(message);
            }
        });
        return true;
    }

    public static boolean postFormDataNet(final Handler mHandler, final String url, final int urlno, RequestBody requestBody) {
        /**
         * 创建 form-data 请求体
         * MultipartBody.Builder builder = new MultipartBody.Builder()
         *         .setType(MultipartBody.FORM)
         *         .addFormDataPart("username", "jack")   // 普通字段
         *         .addFormDataPart("age", "30");
         *
         * 文件字段
         * File file = new File("/sdcard/test.jpg");
         * builder.addFormDataPart("avatar", "test.jpg",
         *         RequestBody.create(file, MediaType.parse("image/jpeg")));
         *
         * 提交的数据
         * RequestBody requestBody = builder.build();
         **/
        registerSerivce.postFormDataNet(url, requestBody,"Bearer " + Constants.AppConstVars.token)
                .enqueue(new Callback<ResponseFormRes>() {
                    @Override
                    public void onResponse(Call<ResponseFormRes> call, Response<ResponseFormRes> response) {
                        //  boolean ispassed=false;
                        Message message = mHandler.obtainMessage();
                        message.arg2 = urlno;
                        message.what = 9901;
                        if (response.isSuccessful()) {
//                    Log.d("postDataNet成功响应", response.body().toString());
                            // 响应成功
                            if (response.body().getCode() == 0) {
//                        Log.d("postDataNet成功返回数据", response.body().toString());
                                // 数据为0，后台正确响应
                                message.what = 9900;
                                message.obj = response.body().getData();
                            }  else if (response.body().getCode() == 401) {
                                message.what = 9904;
                                message.obj = "登录过期，请重新登录";
                                Constants.AppConstVars.token = "";
                                Constants.AppConstVars.sysUser = new SysuserData();
                            } else {
                                // 数据不为0，后台错误响应
                                message.what = 9901;
                                message.obj = response.body().getMsg();
                            }
                        } else {
                            // 超时
                            message.what = 9901;
                            message.obj = "请求失败，请稍后重试";
                        }
                        mHandler.sendMessage(message);
                    }

                    @Override
                    public void onFailure(Call<ResponseFormRes> call, Throwable t) {
                        Message message = mHandler.obtainMessage();
                        message.arg2 = urlno;
                        message.what = 9902;
                        try {
                            if(t instanceof SocketTimeoutException) {
                                message.what = 9901;
                                message.obj = "请求超时，请重试";
                            } else {
                                if (t.getMessage() == null) {
                                    message.obj = t.getClass().toString();
                                } else {
                                    message.obj = t.getMessage();
                                }
                            }

                        } catch (Exception ex) {
                            message.obj = ex.getMessage();
                        }
                        mHandler.sendMessage(message);
                    }
                });
        return true;
    }

    /**
     * 用户登录
     */
    public static boolean loginByPos(String postData, final Handler mHandler, final int urlno) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, postData);
        // loginByPos(body) // registerService里面定义的接口
        registerSerivce.loginByPos(body).enqueue(new Callback<ResponseRes<LoginData>>() {
            @Override
            // 成功进入响应
            public void onResponse(Call<ResponseRes<LoginData>> call, Response<ResponseRes<LoginData>> response) {
                Message message = mHandler.obtainMessage();
                message.arg2 = urlno;
                message.what = 9901;
                Log.d("用户登录,", "返回=" + response.body().getCode() + "," + response.body().getMsg() + ",");
                if (response.isSuccessful()) {
                    // 响应成功
                    Log.d("用户登录,", "返回1=" + response.body().getCode() + "," + response.body().getMsg() + ",");
                    if (response.body().getCode() == 0) {
                        // 数据为0，后台正确响应
                        message.what = 9900;
                         message.obj = response.body().getData();
//                        message.obj = response.body();
                    } else {
                        // 数据不为0，后台错误响应
                        Log.d("shuju", response.body().toString());
                        message.what = 9901;
                        message.obj = response.body().getMsg();
                    }
                } else {
                    // 超时
                    message.what = 9901;
                    message.obj = "请求失败，请稍后重试";
                }
                mHandler.sendMessage(message);
            }

            // 失败响应
            @Override
            public void onFailure(Call<ResponseRes<LoginData>> call, Throwable t) {
                Message message = mHandler.obtainMessage();
                message.arg2 = urlno;
                message.what = 9902;
                try {
                    if(t instanceof SocketTimeoutException) {
                        message.what = 9901;
                        message.obj = "请求超时，请重试";
                    } else {
                        if (t.getMessage() == null) {
                            message.obj = t.getClass().toString();
                        } else {
                            message.obj = t.getMessage();
                        }
                    }

                } catch (Exception ex) {
                    message.obj = ex.getMessage();
                }
                mHandler.sendMessage(message);
            }
        });
        return true;
    }
}